# coding: utf-8
import json
import os
import time
import datetime
import random
import requests
import redis
import sys


class XiechengTicket(object):
    def __init__(self, url='http://flights.ctrip.com/domesticsearch/search/SearchFirstRouteFlights'):
        self.collect_time = datetime.datetime.now().strftime('%Y-%m-%d')
        self.url = url
        self.rd = redis.Redis()
        self.rd2 = redis.Redis(db=1)
        self.rediskey = 'xiecheng_airport'
        self.rediskey_err = 'xiecheng_airport_err'

        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}
        self.user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)

    def parse_code(self, codes):
        _res_codes = []
        for i in codes:
            for j in codes:
                if i != j:
                    _res_codes.append((i, j))
        return _res_codes

    def parse_data(self, codes, dates, cookies, log_token, ck):
        _temp_data = []
        for _code in codes:
            for _date in dates:
                try:
                    _url = '{0}?DCity1={1}&ACity1={2}&SearchType=S&DDate1={3}&LogToken={4}' \
                           '&CK={5}'.format(self.url, _code[0], _code[1], _date, log_token, ck)
                    cookies['FD_SearchHistorty'] = str(cookies['FD_SearchHistorty'])
                    _response = requests.get(_url, headers=self.user_agent, cookies=cookies)
                    time.sleep(random.random() * 2 + 1)
                    _lis = _response.json()['fis']
                    for _li in _lis:
                        _temp = {}
                        _temp['acc'] = _li['acc']
                        _temp['acn'] = _li['acn']
                        _temp['apbn'] = _li['apbn']
                        _temp['at'] = _li['at']
                        _temp['dcc'] = _li['dcc']
                        _temp['dcn'] = _li['dcn']
                        _temp['dpbn'] = _li['dpbn']
                        _temp['dt'] = _li['dt']
                        _temp['fn'] = _li['fn']
                        _temp['pr'] = _li['pr']
                        _temp['tax'] = _li['tax']
                        _temp['cf'] = {'c': _li['cf']['c'], 'dn': _li['cf']['dn'], 's': _li['cf']['s']}
                        _conforts = json.loads(_li['confort'])
                        _temp['confort'] = {
                            'dapart_bridge': _conforts['DepartBridge'],
                            'history_punctuality': _conforts['HistoryPunctuality'],
                            'history_punctuality_arr': _conforts['HistoryPunctualityArr']
                        }
                        _scss = _li['scs']
                        _temp_price = []
                        for _scs in _scss:
                            _temp_scs = {}
                            _temp_scs['rt'] = _scs['rt']
                            _temp_scs['salep'] = _scs['salep']
                            _temp_price.append(_temp_scs)
                        _temp['scs'] = _temp_price
                        _temp['time'] = time.ctime()
                        _temp['url'] = _url
                        # print(_temp)
                        self.rd2.rpush(self.collect_time, _temp)
                except Exception as e:
                    _code = _response.content.decode(encoding='gb18030')
                    self.rd2.rpush(self.rediskey_err, {_url: str(e), 'error': str(_code)})
                    break

    def run(self):
        _datas = self.rd.lrange(self.rediskey, 0, -1)
        _data = json.loads(_datas[0].decode().replace("'{", "{").replace("}'", "}").replace("'", "\""))
        _dates = _data['date']
        _airports = _data['airports']
        _codes = []
        for _airport in _airports:
            _codes.append(_airport['code'])
        _codes = self.parse_code(_codes)
        _cookies, _params = _data['cookie'], _data['param']
        _log_token, _ck = _params['log_token'], _params['ck']
        self.parse_data(_codes, _dates, _cookies, _log_token, _ck)


def main():
    # TODO 未验证
    xc = XiechengTicket()
    xc.run()


if __name__ == '__main__':
    main()
